/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.djinfo.work.activiti.controller;


import com.alibaba.fastjson.JSON;
import com.djinfo.work.activiti.service.ActProcessService;
import com.djinfo.work.common.bean.AjaxJson;
import com.djinfo.work.dao.DictionariesDao;
import com.djinfo.work.entity.Dictionaries;
import com.djinfo.work.util.PageSet;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * 流程定义相关Controller
 * @author ThinkGem
 * @version 2013-11-03
 */
@Controller
@RequestMapping("/actprocess")
public class ActProcessController{

	@Autowired
	private ActProcessService actProcessService;

	@Autowired
	private DictionariesDao dictionariesDao;

	/**
	 * 流程定义列表
	 */
	@RequestMapping(value = "list.do")
	public ModelAndView processList(String category, int current, int pagesize, Model model) {
		/*
		 * 保存两个对象，一个是ProcessDefinition（流程定义），一个是Deployment（流程部署）
		 */
		PageSet<Object[]> page = actProcessService.processList(category, current, pagesize);
		String type="category";
		List<Dictionaries> categoryList =dictionariesDao.processTypeList(type);
		ModelAndView modelAndView= new ModelAndView();
		modelAndView.addObject("page",page);
		modelAndView.addObject("category",category);
		modelAndView.addObject("categoryList",categoryList);
		modelAndView.setViewName("activiti/act/step.jsp");
		return modelAndView;
	}

	/**
	 * 运行中的实例列表
	 */
	@RequestMapping(value = "running.do")
	@ResponseBody
	public AjaxJson runningList(String procInsId, String procDefKey,int current,int pagesize) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson = actProcessService.runningList(procInsId, procDefKey, current, pagesize);
		return ajaxJson;
	}

	/**
	 * 读取资源，通过部署ID
	 * @param procDefId  流程定义ID
	 * @param proInsId 流程实例ID
	 * @param resType 资源类型(xml|image)
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "resourceread.do")
	public void resourceRead(String procDefId, String proInsId, String resType, HttpServletResponse response) throws Exception {
		InputStream resourceAsStream = actProcessService.resourceRead(procDefId, proInsId, resType);
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}

	/**
	 * 部署流程 - 保存
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/deploy2.do", method=RequestMethod.POST)
	public String deploy(@Value("#{configProperties['activiti.export.diagram.path']}") String exportDir,
						 String category, MultipartFile file, RedirectAttributes redirectAttributes) {

		String fileName = file.getOriginalFilename();

		if (StringUtils.isBlank(fileName)){
			redirectAttributes.addFlashAttribute("message", "请选择要部署的流程文件");
		}else{
			String message = actProcessService.deploy(exportDir, category, file);
			redirectAttributes.addFlashAttribute("message", message);
		}

		return "redirect:/actprocess/list.do?category=null&current=1&pagesize=5";
	}
//	/**
//	 * 部署流程 - 保存
//	 * @param file
//	 * @return
//	 */
//	@RequestMapping(value = "/deploy2.do", method= RequestMethod.POST)
//	@ResponseBody
//	public AjaxJson deploy(@Value("#{configProperties['activiti.export.diagram.path']}") String exportDir,
//						 String category, MultipartFile file, RedirectAttributes redirectAttributes) {
//		AjaxJson ajaxJson = new AjaxJson();
//		HashMap<String,Object> map = new HashMap<>();
//		String fileName = file.getOriginalFilename();
//		if (StringUtils.isBlank(fileName)){
//			map.put("message","请选择要部署的流程文件");
////			redirectAttributes.addFlashAttribute("message", "请选择要部署的流程文件");
//		}else{
//			String message = actProcessService.deploy(exportDir, category, file);
////			redirectAttributes.addFlashAttribute("message", message);
//			map.put("message",message);
//		}
//		ajaxJson.setResult(map);
//		return ajaxJson;
//	}


	/**
	 * 设置流程分类
	 */
	@RequestMapping(value = "updateCategory.do")
	public String updateCategory(String procDefId, String category, RedirectAttributes redirectAttributes) {
		actProcessService.updateCategory(procDefId, category);
		return "redirect:/actprocess/list.do?category=null&current=1&pagesize=5";
	}
//	/**
//	 * 设置流程分类
//	 */
//	@RequestMapping(value = "updateCategory.do")
//	public AjaxJson updateCategory(String procDefId, String category, RedirectAttributes redirectAttributes) {
//		AjaxJson ajaxJson = new AjaxJson();
//		actProcessService.updateCategory(procDefId, category);
//		return ajaxJson;
//	}

//	/**
//	 * 挂起、激活流程实例
//	 */
//	@RequestMapping(value = "updatestate.do")
//	public ModelAndView updateState(String state, String procDefId, RedirectAttributes redirectAttributes) {
//		String message = actProcessService.updateState(state, procDefId);
//		redirectAttributes.addFlashAttribute("message", message);
//		return new ModelAndView("redirect:actprocess/second.do");
//	}

	/**
	 * 挂起、激活流程实例
	 */
	@RequestMapping(value = "updatestate.do")
	public String updateState(String state, String procDefId, RedirectAttributes redirectAttributes) {
		String message = actProcessService.updateState(state, procDefId);
		redirectAttributes.addFlashAttribute("message", message);
		return "redirect:/actprocess/list.do?category=null&current=1&pagesize=5";
	}
//	/**
//	 * 挂起、激活流程实例
//	 */
//	@RequestMapping(value = "updatestate.do")
//	@ResponseBody
//	public AjaxJson updateState(String state, String procDefId, RedirectAttributes redirectAttributes) {
//		AjaxJson ajaxJson = new AjaxJson();
//		HashMap<String,Object> map = new HashMap<>();
//		String message = actProcessService.updateState(state, procDefId);
//		map.put("message",message);
////		redirectAttributes.addFlashAttribute("message", message);
//		ajaxJson.setResult(map);
//		return ajaxJson;
//	}

//
//	/**
//	 * 将部署的流程转换为模型
//	 * @param procDefId
//	 * @param redirectAttributes
//	 * @return
//	 * @throws UnsupportedEncodingException
//	 * @throws XMLStreamException
//	 */
//	@RequestMapping(value = "converttoModel.do")
//	public String convertToModel(String procDefId, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException, XMLStreamException {
//		org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId);
//		redirectAttributes.addFlashAttribute("message", "转换模型成功，模型ID="+modelData.getId());
//		return "activiti/model/model.html";
//	}

	/**
	 * 将部署的流程转换为模型
	 * @param procDefId
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws XMLStreamException
	 */
	@RequestMapping(value = "converttoModel.do")
	@ResponseBody
	public AjaxJson convertToModel(String procDefId) throws UnsupportedEncodingException, XMLStreamException {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap<String,Object> map = new HashMap<>();
		try {
			org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId);
			map.put("message","转换模型成功，模型ID="+modelData.getId());
		}catch (Exception e){
			map.put("message","转换模型失败");
			ajaxJson.setCode(201);
			e.printStackTrace();
		}
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	/**
	 * 导出图片文件到硬盘
	 */
	@RequestMapping(value = "exportdiagrams.do")
	@ResponseBody
	public List<String> exportDiagrams(@Value("#{configProperties['activiti.export.diagram.path']}") String exportDir) throws IOException {
		List<String> files = actProcessService.exportDiagrams(exportDir);;
		return files;
	}

	/**
	 * 删除部署的流程，级联删除流程实例
	 * @param deploymentId 流程部署ID
	 */
	@RequestMapping(value = "delete.do")
	public String delete(String deploymentId) {
		actProcessService.deleteDeployment(deploymentId);
		return "redirect:/actprocess/list.do?category=null&current=1&pagesize=5";
	}

//	/**
//	 * 删除部署的流程，级联删除流程实例
//	 * @param deploymentId 流程部署ID
//	 */
//	@RequestMapping(value = "delete.do")
//	@ResponseBody
//	public AjaxJson delete(String deploymentId) {
//		AjaxJson ajaxJson = new AjaxJson();
//		actProcessService.deleteDeployment(deploymentId);
//		return ajaxJson;
//	}


	/**
	 * 添加Flash消息
	 * @param messages
	 */
	protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}

	/**
	 * 删除流程实例
	 * @param procInsId 流程实例ID
	 * @param reason 删除原因
	 */
	@RequestMapping(value = "deleteProcIns.do")
	public String deleteProcIns(String procInsId, String reason, RedirectAttributes redirectAttributes) {
		if (StringUtils.isBlank(reason)){
			addMessage(redirectAttributes, "请填写删除原因");
		}else{
			actProcessService.deleteProcIns(procInsId, reason);
			addMessage(redirectAttributes, "删除流程实例成功，实例ID=" + procInsId);
		}
		return "activiti/act/run.html";
	}

	//	/**
//	 * 删除流程实例
//	 * @param procInsId 流程实例ID
//	 * @param reason 删除原因
//	 */
//	@RequestMapping(value = "deleteProcIns.do")
//	@ResponseBody
//	public AjaxJson deleteProcIns(String procInsId, String reason, RedirectAttributes redirectAttributes) {
//		AjaxJson ajaxJson = new AjaxJson();
//		HashMap<String,Object> map = new HashMap<>();
//		if (StringUtils.isBlank(reason)){
//			map.put("message","请填写删除原因");
////			addMessage(redirectAttributes, "请填写删除原因");
//		}else{
//			actProcessService.deleteProcIns(procInsId, reason);
//			map.put("message","删除流程实例成功，实例ID=" + procInsId);
////			addMessage(redirectAttributes, "删除流程实例成功，实例ID=" + procInsId);
//		}
//		ajaxJson.setResult(map);
//		return  ajaxJson;
//	}
	@RequestMapping(value = "addprocess.do")
	public String addprocess(Model model){
		String type="category";
		List<Dictionaries> categoryList =dictionariesDao.processTypeList(type);
		model.addAttribute("categoryList",categoryList);
		return "activiti/act/add.jsp";
	}

	@RequestMapping(value = "runprocess.do")
	public String runprocess(){
		return "activiti/act/run.html";
	}
}
